﻿using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace SerialManager.Loaders
{
    public class TvRageLoader : EpisodeWebLoader
    {
        private static readonly Regex EpisodeNumberExp
            = new Regex( "([0-9]{1,2})x([0-9]{1,2})", RegexOptions.Singleline | RegexOptions.Compiled );

        protected override Uri Address
        {
            get { return new Uri( "http://www.tvrage.com/" + SerialName.Replace( " ", "_" ) + "/episode_list/all" ); }
        }

        protected override void OnXmlLoaded( XElement doc )
        {
            var content = (
                from td in doc.Descendants( XNTableCell )
                where td.GetAttributeValueOrEmpty( XNClass ) == "editcenterbox"
                select td
            ).First();

            if( Aborted )
                return;

            var seasonTables = (
                from table in content.Descendants( XNTable )
                where table.GetAttributeValueOrEmpty( XNClass ) == "b"
                select table.Elements( XNTableRow )
            );

            if( Aborted )
                return;

            seasonTables.ToList().ForEach( AddSeason );
            Status = EpisodeLoaderStatus.DoneSuccessful;
        }

        private void AddSeason( IEnumerable<XElement> episodes )
        {
            if( Aborted )
                return;

            SeasonCount++;

            Episodes.AddRange(
                from episode in episodes
                let cells = episode.Elements( XNTableCell )
                let fullnumber = EpisodeNumberExp.Match( cells.ElementAt( 1 ).Value )
                where fullnumber.Success
                select new EpisodeInfo
                {
                    Season = Convert.ToInt32( fullnumber.Groups[ 1 ].Value ),
                    Number = Convert.ToInt32( fullnumber.Groups[ 2 ].Value ),
                    Title = cells.ElementAt( 4 ).Value
                }
            );
        }
    }
}
